<?php

/**
 * 后台Controller
 */
namespace Common\Controller;

use Common\Controller\AppframeController;
use Think\Cache\Driver\Redis;

class AdminbaseController extends AppframeController
{

    public function __construct()
    {
        $admintpl_path = C("SP_ADMIN_TMPL_PATH") . C("SP_ADMIN_DEFAULT_THEME") . "/";
        C("TMPL_ACTION_SUCCESS", $admintpl_path . C("SP_ADMIN_TMPL_ACTION_SUCCESS"));
        C("TMPL_ACTION_ERROR", $admintpl_path . C("SP_ADMIN_TMPL_ACTION_ERROR"));
        parent::__construct();
        $time = time();
        $this->assign("js_debug", APP_DEBUG ? "?v=$time" : "");
    }

    function _initialize()
    {
        parent::_initialize();
        $this->load_app_admin_menu_lang();
        if (isset($_SESSION['ADMIN_ID'])) {
            $users_obj = M("AdminUser");
            $id = $_SESSION['ADMIN_ID'];
            $user = $users_obj->where("admin_id=$id")->find();
//            if (!$this->check_access($id)) {
//                $this->error("您没有访问权限！");
//                exit();
//            }
            $this->assign("admin", $user);
        } else {
            //$this->error("您还没有登录！",U("admin/public/login"));
            if (IS_AJAX) {
                $this->error("您还没有登录！", U("admin/public/login"));
            } else {
                header("Location:" . U("admin/public/login"));
                exit();
            }

        }
    }

    /**
     * 初始化后台菜单
     */
    public function initMenu()
    {
        $Menu = M("SysMenu",null);
        if (!$Menu) {
            $Menu = D("Common/SysMenu")->menu_cache();
        }
        return $Menu;
    }

    /**
     * 消息提示
     * @param type $message
     * @param type $jumpUrl
     * @param type $ajax
     */
    public function success($message = '', $jumpUrl = '', $ajax = false)
    {
        parent::success($message, $jumpUrl, $ajax);
    }

    /**
     * 模板显示
     * @param type $templateFile 指定要调用的模板文件
     * @param type $charset 输出编码
     * @param type $contentType 输出类型
     * @param string $content 输出内容
     * 此方法作用在于实现后台模板直接存放在各自项目目录下。例如Admin项目的后台模板，直接存放在Admin/Tpl/目录下
     */
    public function display($templateFile = '', $charset = '', $contentType = '', $content = '', $prefix = '')
    {
        if ($templateFile==''){
            //获取子类的调用方法名称
            $arr = debug_backtrace();
            if (count($arr)>1){
                $templateFile = $arr[1]['function'];
            }
        }
        parent::display($this->parseTemplate($templateFile), $charset, $contentType);
    }

    /**
     * 获取输出页面内容
     * 调用内置的模板引擎fetch方法，
     * @access protected
     * @param string $templateFile 指定要调用的模板文件
     * 默认为空 由系统自动定位模板文件
     * @param string $content 模板输出内容
     * @param string $prefix 模板缓存前缀*
     * @return string
     */
    public function fetch($templateFile = '', $content = '', $prefix = '')
    {
        $templateFile = empty($content) ? $this->parseTemplate($templateFile) : '';
        return parent::fetch($templateFile, $content, $prefix);
    }

    /**
     * 自动定位模板文件
     * @access protected
     * @param string $template 模板文件规则
     * @return string
     */
    public function parseTemplate($template = '')
    {
        $tmpl_path = C("SP_ADMIN_TMPL_PATH");
        define("SP_TMPL_PATH", $tmpl_path);
        // 获取当前主题名称
        $theme = C('SP_ADMIN_DEFAULT_THEME');

        if (is_file($template)) {
            // 获取当前主题的模版路径
            define('THEME_PATH', $tmpl_path . $theme . "/");
            return $template;
        }
        $depr = C('TMPL_FILE_DEPR');
        $template = str_replace(':', $depr, $template);

        // 获取当前模块
        $module = MODULE_NAME . "/";
        if (strpos($template, '@')) { // 跨模块调用模版文件
            list($module, $template) = explode('@', $template);
        }
        // 获取当前主题的模版路径
        define('THEME_PATH', $tmpl_path . $theme . "/");

        // 分析模板文件规则
        if ('' == $template) {
            // 如果模板文件名为空 按照默认规则定位
            $template = CONTROLLER_NAME . $depr . ACTION_NAME;
        } elseif (false === strpos($template, '/')) {
            $template = CONTROLLER_NAME . $depr . $template;
        }

        C("TMPL_PARSE_STRING.__TMPL__", __ROOT__ . "/" . THEME_PATH);

        C('SP_VIEW_PATH', $tmpl_path);
        C('DEFAULT_THEME', $theme);
        define("SP_CURRENT_THEME", $theme);

        $file = sp_add_template_file_suffix(THEME_PATH . $module . $template);
        $file = str_replace("//", '/', $file);
        if (!file_exists_case($file)) E(L('_TEMPLATE_NOT_EXIST_') . ':' . $file);
        return $file;
    }

    /**
     *  排序 排序字段为listorders数组 POST 排序字段为：listorder
     */
    protected function _listorders($model)
    {
        if (!is_object($model)) {
            return false;
        }
        $pk = $model->getPk(); //获取主键名称
        $ids = $_POST['listorders'];
        foreach ($ids as $key => $r) {
            $data['listorder'] = $r;
            $model->where(array($pk => $key))->save($data);
        }
        return true;
    }

    /**
     * 后台分页
     *
     */
    protected function page($total_size = 1, $page_size = 0, $current_page = 1, $listRows = 6, $pageParam = '', $pageLink = '', $static = FALSE)
    {
        if ($page_size == 0) {
            $page_size = C("PAGE_LISTROWS");
        }

        if (empty($pageParam)) {
            $pageParam = C("VAR_PAGE");
        }

        $Page = new \Page($total_size, $page_size, $current_page, $listRows, $pageParam, $pageLink, $static);
        $Page->SetPager('Admin', '{first}{prev}&nbsp;{liststart}{list}{listend}&nbsp;{next}{last}', array("listlong" => "9", "first" => "首页", "last" => "尾页", "prev" => "上一页", "next" => "下一页", "list" => "*", "disabledclass" => ""));
        return $Page;
    }

    private function check_access($uid)
    {
        //如果用户角色是1，则无需判断
        if ($uid == 1) {
            return true;
        }

        $rule = MODULE_NAME . CONTROLLER_NAME . ACTION_NAME;
        $no_need_check_rules = array("AdminIndexindex", "AdminMainindex");

        if (!in_array($rule, $no_need_check_rules)) {
            return sp_auth_check($uid);
        } else {
            return true;
        }
    }

    private function load_app_admin_menu_lang()
    {
        if (C('LANG_SWITCH_ON', null, false)) {
            $admin_menu_lang_file = SPAPP . MODULE_NAME . "/Lang/" . LANG_SET . "/admin_menu.php";
            if (is_file($admin_menu_lang_file)) {
                $lang = include $admin_menu_lang_file;
                L($lang);
            }
        }
    }

    public function exportExcel($expTitle, $expCellName, $expTableData)
    {
        $xlsTitle = $expTitle . date('_YmdHis');//or $xlsTitle 文件名称可根据自己情况设定
        $fileName = iconv('utf-8', 'gbk', $xlsTitle);//文件名称
        $cellNum = count($expCellName);
        $dataNum = count($expTableData);
        vendor("PHPExcel.PHPExcel");

        $objPHPExcel = new \PHPExcel();
        $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');
        $ua = $_SERVER["HTTP_USER_AGENT"];
        $objPHPExcel->getActiveSheet(0)->setTitle($expTitle);
        $objPHPExcel->getActiveSheet(0)->mergeCells('A1:' . $cellName[$cellNum - 1] . '1');//合并单元格
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('A1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        for ($i = 0; $i < $cellNum; $i++) {
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i] . '2', $expCellName[$i][1]);
        }
        // Miscellaneous glyphs, UTF-8
        for ($i = 0; $i < $dataNum; $i++) {
            for ($j = 0; $j < $cellNum; $j++) {
                $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j] . ($i + 3), $expTableData[$i][$expCellName[$j][0]]);
            }
        }

        header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="' . $xlsTitle . '.xls"');
        header("Content-Disposition:attachment;filename=$fileName.xls");//attachment新窗口打印inline本窗口打印
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }
    
    public function curl_http($url, $post_data = '', $header=array(), $timeout=30){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
		curl_setopt($ch, CURLOPT_URL, $url);
		$header[] = 'Content-Type:application/x-www-form-urlencoded';
		$header[] = 'Accept-Charset: utf-8';
		curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
		if(!empty($post_data)){
			curl_setopt($ch, CURLOPT_POST, true);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
		}
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
		curl_setopt($ch, CURLOPT_HEADER, false);
		curl_setopt($ch, CURLOPT_DNS_USE_GLOBAL_CACHE, false);
		$response = curl_exec($ch);
	
		if($error = curl_error($ch)){
			die($error);
		}
	
		curl_close($ch);

		\Think\Log::record($url.$post_data.'--response：'.$response, 'INFO');
		return json_decode($response, true);
	}

    protected function _checkMobile($mobile)
    {
        if (preg_match("/^1[34578]\d{9}$/", $mobile)) {
            return true;
        } else {
            return false;
        }
    }

    public function  saveQRCode($url)
    { //二维码图片保存路径
        $pathname = date("Ymd", time());
        $pathname = C("TMPL_PARSE_STRING.__UPLOAD__") . "qrcode/" . $pathname;
        if (!is_dir($pathname)) { //若目录不存在则创建之
            $r = mkdir($pathname);
        }
        //echo $pathname;die();
        vendor("phpqrcode.phpqrcode");

        //二维码URL参数
        $text = $url;
        //二维码图片保存路径(若不生成文件则设置为false)
        $filename = "." . $pathname . "/qrcode_" . time() . ".png";

        $returnName = $pathname . "/qrcode_" . time() . ".png";
        //echo $filename;die();
        //二维码容错率，默认L
        $level = "L";
        //二维码图片每个黑点的像素，默认4
        $size = '10';
        //二维码边框的间距，默认2
        $padding = 2;
        //保存二维码图片并显示出来，$filename必须传递文件路径
        $saveandprint = true;

        //生成二维码图片
        \QRcode::png($text, $filename, $level, $size, $padding, $saveandprint);
        return $returnName;
    }
    
    function getRange($cnt=9){
    	$numbers = range (1,$cnt);
    	//播下随机数发生器种子，可有可无，测试后对结果没有影响
    	srand ((float)microtime()*1000000);
    	shuffle ($numbers);
    	//跳过list第一个值（保存的是索引）
    	$n = '';
    	while (list(, $number) = each ($numbers)) {
    		$n .="$number";
    	}
    	return $n;
    }
    
    /**
     *  获取新闻类型
     */
    public function _getNewType($val){
    	if(!$val['type'] || $val['type'] == 0){
    		return '未知';
    	}
    	if($val['type'] == 1){
    		return '快捷发布';
    	}elseif($val['type'] == 2){
    		return '轮播图';
    	}elseif($val['type'] == 3){
    		return '专题';
    	}elseif($val['type'] == 4){
    		if($val['video_category'] == 1 || empty($val['video_category'])){
    			return '普通视频';
    		}else{
    			return 'VR视频';
    		}
    	}elseif($val['type'] == 5){
    		return '图集';
    	}elseif($val['type'] == 6){
    		return '文本';
    	}elseif($val['type'] == 7){
    		/* if($val['cover_image']){
    		 return '图文';
    		 }else{
    		 return '文本';
    		 } */
    		return '图文';
    	}elseif($val['type'] == 9){
            return '视频直播';
        }elseif($val['type'] == 10){
            return 'VR直播';
        }elseif($val['type'] == 11){
            return '图文直播';
        }elseif($val['type'] == 12){
            return '视频加图文直播';
        }elseif($val['type'] == 13){
            return 'VR加图文直播';
        }elseif($val['type'] == 14){
            return '录播';
        }else{
    		return '未知';
    	}
    }
    
    function sign($array){
        if(!empty($array['sign'])){
            unset($array['sign']);
        }
        ksort($array);
        $string="";
        while (list($key, $val) = each($array)){
            $string .= $key.'='.$val.'&';
        }
        $string = rtrim($string, '&');
//        echo md5($string);exit();
        return md5($string);
    }

    public function handleImage($content){
        $content = json_decode($content);
        $content = preg_replace('/(src=\"http:\/\/vrlive-.*?(jpg|png|jpeg))\"/', '$1/y"', $content);
        return $content;
    }
    
    
    /**
     * 获取管理员权限
     */
    public function getAdminRole($admin_id){
        //查看该管理员权限并存入redis
        $action_list = array();
        $admin_role_obj = M("vradmin1.admin_role", null);
        $admin_role = $admin_role_obj->where(['admin_id' => $admin_id])->select();

        if ($admin_role && count($admin_role) > 0) {
            $role_ids = array_column($admin_role, 'role_id');
            if (count($role_ids) > 0) {
                $role_id = implode(',', $role_ids);
                $relation = M("vradmin1.role_power_relation", null);
                $role_power_relation = $relation->where("role_id in (" . $role_id . ")")->select(); //角色权限关系数据
                $action_ids_arr = array_filter(array_column($role_power_relation, 'action_ids'));
                if (count($action_ids_arr) > 0) {
                    $action_ids = implode(',', $action_ids_arr);
                    $power_action = M("vradmin1.power_action", null);
                    $action_list = $power_action->where("action_id in (" . $action_ids . ")")->field("action_id, action_name")->select();
                }
            }
        }
        $redis = new Redis();
        $name = C('environment') . '_admin_role_' . $admin_id;
        $key = $redis->buildKey($name);
        $redis->set_redis($key, $action_list);
        return $action_list;
    }
}